package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.vo.InvoiceVo;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.FileUploadUtil;
import cn.itcast.web.utils.SerialNumberUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @AuThor：zengxing
 * @DATE:2020/12/25 11:01  250
 */
@Controller
@RequestMapping("/cargo/invoice")
public class InvoiceController extends BaseController {
    @Reference
    private ShippingOrderService shippingOrderService;

    @Reference
    private PackingService packingService;

    @Reference
    private InvoiceService invoiceService;

    @Reference
    private ExportService exportService;

    @Reference
    private ContractService contractService;

    @Reference
    private ExportProductService exportProductService;

    @Reference
    private ExtEproductSerivce extEproductSerivce;

    @Autowired
    private FileUploadUtil fileUploadUtil;
    /**
     * 进入添加页面
     */
    @RequestMapping("/toAdd")
    public String toAdd(String id) {
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        PackingList packingList = packingService.findBypackingId(id);
        String exportIds = packingList.getExportIds();
        String tradeTerms = "";
        double amount = 0;
        if (exportIds != null) {
            String[] ids = exportIds.split(",");
            if (ids != null && ids.length > 0) {
                for (String s : ids) {
                    Export export = exportService.findById(s);
                    String contractIds = export.getContractIds();
                    if (contractIds != null) {
                        String[] contracts = contractIds.split(",");
                        if (contracts != null && contracts.length > 0) {
                            for (String contract : contracts) {
                                Contract con = contractService.findById(contract);
                                tradeTerms += con.getTradeTerms()+",";
                                if(con!=null&&con.getTotalAmount()!=null){
                                    amount += con.getTotalAmount();
                                }
                            }
                        }
                    }
                }
                tradeTerms = tradeTerms.substring(0, tradeTerms.length() - 1);
            }
        }

        if(packingList.getPackingMoney()!=null){
            amount += packingList.getPackingMoney();
        }
        if(shippingOrder.getShippingMoney()!=null){
            amount += shippingOrder.getShippingMoney();
        }
        Invoice invoice = new Invoice();
        invoice.setId(shippingOrder.getShippingOrderId());
        invoice.setScNo(packingList.getExportNos());
        invoice.setTradeTerms(tradeTerms);
        invoice.setInvoiceMoney(amount);
        request.setAttribute("invoice",invoice);
        return "cargo/invoice/invoice-add";
    }

    /**
     * 添加或修改
     */
    @RequestMapping("/edit")
    public String edit(Invoice invoice, MultipartFile pickupImage) {
        // 设置企业信息（从登陆用户中获取
        invoice.setCompanyId(getLoginCompanyId());
        invoice.setCompanyName(getLoginCompanyName());
        ShippingOrder shippingOrder = shippingOrderService.findById(invoice.getId());
        if(shippingOrder.getState()==0){
            try {
                String url = "http://"+fileUploadUtil.upload(pickupImage);
                if(url==null){
                    invoice.setPickupPhoto("");
                }
                invoice.setPickupPhoto(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            invoice.setInvoiceNo(SerialNumberUtil.Getnum());
            invoiceService.save(invoice);
        }
        return "redirect:/cargo/shipping/list";
    }

    /**
     * 添加或修改
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5")Integer pageSize) {
        // 设置企业信息（从登陆用户中获取
        PageInfo pageInfo = invoiceService.findByPage(getLoginCompanyId(), pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "/cargo/invoice/invoice-list";
    }

    @RequestMapping("checkState")
    @ResponseBody
    public Map<String,Integer> checkState(String id){
        // 返回的数据通过map封装
        Map<String,Integer> resultMap = new HashMap<>();
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        if (shippingOrder.getState()==0){
            resultMap.put("message",1);
        } else {
            resultMap.put("message",0);
        }
        return resultMap;
    }

    /**
     * 删除
     * 返回的json：{message:1}
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Map<String,Integer> delete(String id){
        // 返回的数据通过map封装
        Map<String,Integer> resultMap = new HashMap<>();
        Invoice invoice = invoiceService.findById(id);
        if(invoice.getStatus()==0){
            invoiceService.delete(id);
            resultMap.put("message",1);
        }else {
            resultMap.put("message",0);
        }
        return resultMap;
    }

    @RequestMapping("/printPdf")
    public void printPdf(String id) throws Exception {
        ShippingOrder shippingOrder = shippingOrderService.findById(id);
        PackingList packingList = packingService.findBypackingId(id);
        HashMap<String, Object> map = new HashMap<>();
        Invoice invoice = invoiceService.findById(id);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(invoice.getInvoiceTime());
        map.put("inputDate",dateString);
        map.put("invoiceNo", invoice.getInvoiceNo());
        map.put("seller", getLoginCompanyName());
        map.put("buyer", packingList.getBuyer());
        String exportIds = packingList.getExportIds();
        List<InvoiceVo> list = new ArrayList<>();
        InvoiceVo shipping = new InvoiceVo();
        shipping.setProductNo(shippingOrder.getShippingOrderId());
        shipping.setType("委托");
        shipping.setCnumber(1);
        shipping.setPrice(shippingOrder.getShippingMoney());
        list.add(shipping);
        InvoiceVo packing = new InvoiceVo();
        packing.setProductNo(packingList.getPackingListId());
        packing.setType("装箱");
        packing.setCnumber(1);
        packing.setPrice(packingList.getPackingMoney());
        list.add(packing);
        if (exportIds != null) {
            String[] ids = exportIds.split(",");
            if (ids != null && ids.length > 0) {
                for (String s : ids) {
                    Export export = exportService.findById(s);
                    List<ExportProduct> productList = exportProductService.findByExportId(export.getId());
                    List<ExtEproduct> extEproductList = extEproductSerivce.findByExportId(export.getId());
                    for (ExportProduct product : productList) {
                        InvoiceVo invoiceVo = new InvoiceVo();
                        invoiceVo.setProductNo(product.getProductNo());
                        invoiceVo.setType("商品");
                        invoiceVo.setCnumber(product.getCnumber());
                        invoiceVo.setPrice(product.getPrice());
                        list.add(invoiceVo);
                    }
                    for (ExtEproduct extEproduct : extEproductList) {
                        InvoiceVo invoiceVo = new InvoiceVo();
                        invoiceVo.setProductNo(extEproduct.getProductNo());
                        invoiceVo.setType("附件");
                        invoiceVo.setCnumber(extEproduct.getCnumber());
                        invoiceVo.setPrice(extEproduct.getPrice());
                        list.add(invoiceVo);
                    }
                }
            }
        }
        InputStream in =
                session.getServletContext()
                        .getResourceAsStream("/jasper/invoice.jasper");

        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(list);
        JasperPrint jasperPrint =
                JasperFillManager.fillReport(in, map, dataSource);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-disposition","attachment;fileName=invoice.pdf");
        ServletOutputStream out = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, out);
        out.close();
    }

    @RequestMapping("/setStatus")
    public String setStatus(String id){
        Invoice invoice = invoiceService.findById(id);
        invoice.setStatus(1);
        invoiceService.update(invoice);
        return "redirect:/cargo/invoice/list";
    }
}
